<?php
/** 
 * @package AMFramework
 * @subpackage Data_Pack
 * @author Marcu Alexandru
 * @version 1.0 $Build 305b  
 */
defined('_INDEX') or die('Restricted');

class Amfw_Factory {
	public static function &getDb() {
		static $db_inst;
		if(!isset($db_inst)) {
			$db_inst = self::_createDb();
		}

		return $db_inst;
	}
	
	private static function _createDb() 
	{
		$app = Amfw_Application::_();
		// Am descarcat configuratia aplicatiei pentru a sti de ce clasa avem nevoie,
		// daca configuratia nu exista - mai jos vom crea o eroare
		$connection = @$app->database['connection'];

		// Daca este true, configuratia nu exista
		if(!isset($connection)) {
			$msg= '<b>Database configuration doesn`t exist</b> in current ApplicationSetup.ini';
			Amfw_Debug::toJournal($msg,D_ERROR,1);
		}
		
		$className = 'Amfw_Database_'.ucfirst(strtolower($connection));
		if(class_exists($className)) {
			$dbo = new $className;
			$dbo->init();
			return $dbo;
		}
		
		return null;
	}
	
	
	/** NOTE:
	 * Desi seamana preluarea unui table din Model, cu preluarea din Ctrl a Modelului
	 * se va folosi Factory; diferenta este ca tabelele sunt independente de model
	 * spre deosebire de modelul de controller (unde avem asociere 1-1), aici avem
	 * asociere n-n: oricate tabele pot fi folosite de oricate modele, factory pastreaza
	 * static intr-un array istantele fiecarui tabel cerut;
	 * @param Array $name	Numele tabelului ce se creaza, despartit in tokenuri; 
	 */
	public static function &getTable( $name ) {
		if(!is_array($name)){
			$name = explode('_',$name);
		}
		$tokens = $name;
		$size 	= count($tokens);
		$table	= $tokens[$size-1];
		$folder = $tokens[$size-2] == 'Table' ? null : $tokens[$size-2];  

		static $tables;

		if(isset($folder)) 
		{
			if(!isset($tables[$folder][$table])): 
				$class = implode('_',$tokens);
				$tables[$folder][$table] = new $class();
				endif;

			return $tables[$folder][$table];
		}
		else 
		{
			if(!isset($tables[$table])):
				$class = implode('_',$tokens);
				$tables[$table]= new $class();
				endif;

			return $tables[$table];
		}

		return null;
	}
	
	public static function &getSession() {
		//return Amfw_Session::getInstance();
		static $sessionInst;
		if(!isset($sessionInst)) { $sessionInst = self::_createSession(); }
		return $sessionInst;
	}
	
	static function &_createSession() {
		$session=new Amfw_Session();
		$session->start();
		return $session;
	}
	
	public static function &getDocument() {

		static $doc;
		if(!isset($doc)):
			global $framework;
			$doc = $framework->getDocument();
			endif;
		return $doc;
	}
	
	public static function &getTemplate() {

	}
}